package sun.cn.common.utils;

import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.annotation.*;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * @descript:
 * @see:
 * @date:2018-07-02
 * @author:sunla
 */
public final class DtoSmallUtils {

    private static final Logger LOG = LoggerFactory.getLogger(DtoSmallUtils.class);

    private  DtoSmallUtils (){}

    public static <E> List<E> comeListToSmall(List<E> list){
        if(CollectionUtils.isNotEmpty(list)){
            List<E> result = new ArrayList<E>(list.size());
            for(E e : list){
                result.add(comeObjectToSmaill(e));
            }
            return result;
        }
        return null;
    }

    public static <E> E comeObjectToSmaill(E e){
        if( e == null) return null;
        Field[] fields = e.getClass().getDeclaredFields();
        for(Field field : fields){
            Annotation smallAnnotation = field.getAnnotation(Small.class);
            if(smallAnnotation != null){
                field.setAccessible(true);
				/** 判断是否为基本类型 和 字符串类型 */
                if(!field.getType().isPrimitive() || field.getType().equals(String.class)){
                    try {
                        field.set(e,null);
                    } catch (IllegalAccessException e1) {
                        LOG.error("comeObjectToSmaill error msg is {}",e);
                    }
                }
            }
        }
        return e;
    }

    @Target({ElementType.FIELD})
    @Retention(RetentionPolicy.RUNTIME)
    @Inherited
    @Documented
    public @interface Small{

    }
}
